// websocket状态管理

import { defineStore } from 'pinia';
import { getConnect } from '@/api/socket';
import $eventBus from '@/utils/eventBus';

const state = {
  msg: '',
  websocketId: '',
  webSocket: WebSocket,
};

export const useWebsocketStore = defineStore('msg', {
  state: () => state,
  getters: {
    ws: (state) => {
      return state.webSocket;
    },
    wsId: (state) => {
      return state.websocketId;
    },
  },
  actions: {
    createConnect() {
      var id = localStorage.getItem('websocketId') ?? '';
      getConnect({ websocketId: id }).then((ret) => {
        console.log('websocket', JSON.stringify(ret));
        this.websocketId = ret.result.websocketId;
        localStorage.setItem('websocketId', this.websocketId);
        console.log('state', JSON.stringify(state));
        this.openWS(ret.result.server);
      });
    },
    openWS(url: string) {
      this.webSocket = new WebSocket(url);
      this.webSocket.addEventListener('open', () => {
        console.log('ws connect is open ');
      });
      // 收到消息的回调
      this.webSocket.addEventListener('message', (data: any) => {
        this.message(data);
      });
      // 关闭连接时的提示
      this.webSocket.addEventListener('close', () => {
        console.log('ws connect is close');
        this.reConnect()
      });
    },
    message(d: any) {
      console.log('======收到消息=====');
      console.log(d);
      $eventBus.emit('receiveMsgEvent', d.data);
      state.msg = d.data;
    },
    // 发送信息的处理函数, 先判断连接是否打开, 然后再发送
    sendMsg(msg: string) {
      if (this.webSocket.readyState == 1) {
        this.webSocket.send(msg);
      } else {
        console.log(this.webSocket.readyState);
      }
    },
    // 单击按钮手动进行重新连接
    reConnect() {
      console.log('重新连接中...');
      this.createConnect();
    },
    getWebsocketId() {
      let websocketId = localStorage.getItem('websocketId');
      return websocketId;
    },
  },
});
